package com.quzi.kettle.push;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.internal.MemoryPersistence;

import android.content.Context;

import com.quzi.kettle.GlobalConfig;
import com.quzi.kettle.utils.MSharePerference;

public class Thermometer {

	private static Thermometer instance;

	public static Thermometer getInstance(Context context) {
		if (instance == null) {
			instance = new Thermometer(context);
		}
		return instance;
	}

	private MqttClient client;
	private Context context;
	private Thermometer(Context context) {
		this.context = context;
		try {
			client = new MqttClient(GlobalConfig.BROKER_URL,
					MqttClient.generateClientId(), new MemoryPersistence());
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}

	public void sendControlText(final String str) {

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					MqttConnectOptions options = new MqttConnectOptions();
					options.setCleanSession(true);
					options.setConnectionTimeout(5000);
					options.setUserName(GlobalConfig.userName);
					options.setPassword(GlobalConfig.passWord.toCharArray());

					client.connect(options);
					publishData(str);
					client.disconnect();
				} catch (MqttException e) {
					e.printStackTrace();
					System.exit(1);
				}
			}
		}).start();
	}
	
	public void sendControlText(final byte[] bytes) {

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					MqttConnectOptions options = new MqttConnectOptions();
					options.setCleanSession(true);
					options.setConnectionTimeout(5000);
					options.setUserName(GlobalConfig.userName);
					options.setPassword(GlobalConfig.passWord.toCharArray());

					client.connect(options);
					publishData(bytes);
					client.disconnect();
				} catch (MqttException e) {
					e.printStackTrace();
					System.exit(1);
				}
			}
		}).start();
	}

	private void publishData(String str) throws MqttException {
		final MqttTopic sendTopic = client.getTopic(getSendTopic());
		final MqttMessage message = new MqttMessage(str.getBytes());
		sendTopic.publish(message);
	}

	private void publishData(byte[] bytes) throws MqttException {
		final MqttTopic sendTopic = client.getTopic(getSendTopic());
		final MqttMessage message = new MqttMessage(bytes);
		sendTopic.publish(message);
	}
	
	
	private String getSendTopic() {
		// TODO Auto-generated method stub
		return GlobalConfig.Filter_Receive + MSharePerference.getInstance(context).get(GlobalConfig.MAC);
	}

}
